# coding: utf-8
import sys

from PySide6.QtCore import Qt, QEvent
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QHBoxLayout, QWidget
from qfluentwidgets import TransparentToolButton, FluentIcon, IconWidget, BodyLabel, setFont, FluentStyleSheet, \
    toggleTheme
from qframelesswindow import TitleBarButton
from qframelesswindow.titlebar.title_bar_buttons import TitleBarButtonState
from qframelesswindow.utils import startSystemMove, toggleMaxState

from ...common import Icon


class MaximizeButton(TransparentToolButton):
    def _postInit(self):
        super()._postInit()
        self._state = TitleBarButtonState.NORMAL

    def setMaxState(self, isMax: bool):
        if isMax:
            self.setIcon(Icon.MAXIMIZE_OFF)
        else:
            self.setIcon(Icon.MAXIMIZE_ON)

    def setState(self, state: TitleBarButtonState):
        self._state = state
        self.update()


class TitleBarBase(QWidget):
    """ Title bar base class """

    def __init__(self, parent):
        super().__init__(parent)
        self.minBtn = TransparentToolButton(Icon.MINIMIZE, self)
        self.maxBtn = MaximizeButton(Icon.MAXIMIZE_ON, self)
        self.closeBtn = TransparentToolButton(FluentIcon.CLOSE, self)

        self._isDoubleClickEnabled = True

        self.setFixedHeight(50)

        # connect signal to slot
        self.minBtn.clicked.connect(self.window().showMinimized)
        self.maxBtn.clicked.connect(self.__toggleMaxState)
        self.closeBtn.clicked.connect(self.window().close)

        self.window().installEventFilter(self)

    def eventFilter(self, obj, e):
        if obj is self.window():
            if e.type() == QEvent.Type.WindowStateChange:
                self.maxBtn.setMaxState(self.window().isMaximized())
                return False

        return super().eventFilter(obj, e)

    def mouseDoubleClickEvent(self, event):
        """ Toggles the maximization state of the window """
        if event.button() != Qt.MouseButton.LeftButton or not self._isDoubleClickEnabled:
            return

        self.__toggleMaxState()

    def mouseMoveEvent(self, e):
        if sys.platform != "win32" or not self.canDrag(e.pos()):
            return

        startSystemMove(self.window(), e.globalPos())

    def mousePressEvent(self, e):
        if sys.platform == "win32" or not self.canDrag(e.pos()):
            return

        startSystemMove(self.window(), e.globalPos())

    def __toggleMaxState(self):
        """ Toggles the maximization state of the window and change icon """
        toggleMaxState(self.window())

    def _isDragRegion(self, pos):
        """ Check whether the position belongs to the area where dragging is allowed """
        width = 0
        for button in self.findChildren(TitleBarButton):
            if button.isVisible():
                width += button.width()

        return 0 < pos.x() < self.width() - width

    def _hasButtonPressed(self):
        """ whether any button is pressed """
        return any(btn.isPressed() for btn in self.findChildren(TitleBarButton))

    def canDrag(self, pos):
        """ whether the position is draggable """
        return self._isDragRegion(pos) and not self._hasButtonPressed()

    def setDoubleClickEnabled(self, isEnabled):
        """ whether to switch window maximization status when double clicked
        Parameters
        ----------
        isEnabled: bool
            whether to enable double click
        """
        self._isDoubleClickEnabled = isEnabled


class CustomToolTitleBar(TitleBarBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.__isTop = False
        self.horizontalLayout = QHBoxLayout(self)
        self.iconLabel = IconWidget(self)
        self.titleLabel = BodyLabel(self)

        self.themeBtn = TransparentToolButton(FluentIcon.CONSTRACT, self)


        self.__initWidgets()
        self.__initLayout()
        self.__connectSignals()

    def __initWidgets(self):
        self.setFixedHeight(48)
        setFont(self.titleLabel, 13)

        FluentStyleSheet.FLUENT_WINDOW.apply(self)

    def __initLayout(self):
        self.iconLabel.setFixedSize(18, 18)

        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter)
        self.horizontalLayout.setContentsMargins(10, 0, 10, 0)
        self.horizontalLayout.addWidget(self.iconLabel)
        self.horizontalLayout.addWidget(self.titleLabel)
        self.horizontalLayout.addStretch(1)
        self.horizontalLayout.addWidget(self.themeBtn)
        self.horizontalLayout.addWidget(self.minBtn)
        self.horizontalLayout.addWidget(self.maxBtn)
        self.horizontalLayout.addWidget(self.closeBtn)

    def setTitle(self, title):
        self.titleLabel.setText(title)
        self.titleLabel.adjustSize()

    def setIcon(self, icon):
        self.iconLabel.setIcon(QIcon(icon))

    def __connectSignals(self):
        self.window().windowIconChanged.connect(self.setIcon)
        self.window().windowTitleChanged.connect(self.setTitle)
        self.themeBtn.clicked.connect(lambda: toggleTheme(save=True, lazy=True))
